//
//  TickectDetailVC.m
//  ImGuider
//
//  Created by 王鹏宇 on 2018/1/3.
//  Copyright © 2018年 imguider. All rights reserved.
//

#import "TickectDetailVC.h"
#import "TicketIntroduceCell.h"
#import "TicketInforTipCell.h"
#import "TicketBookingCell.h"
#import "TicketScenicCell.h"
#import "TicketPurchaseTipCell.h"
#import "SectionTitleHeaderView.h"
#import "TicketOrderVC.h"
#import "TicketDetailModel.h"

#import "WPYNavBar.h"
@interface TickectDetailVC ()<UITableViewDataSource,UITableViewDelegate,SnailSheetViewDelegate,WPYNavBarDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (nonatomic, strong)UIImageView * TicketImageView;

@property (nonatomic, strong)UIButton * tipBtn;

@property (nonatomic, strong)TicketDetailModel * ticketDetailModel;

@property (weak, nonatomic) IBOutlet UIButton *reservationBtn;

@property (nonatomic, strong)WPYNavBar * sectionView;

@property (nonatomic, assign)BOOL isDrag;
@end

@implementation TickectDetailVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    
    [self setup];
    [self loadData];
}

- (void)setNavItem {
    
    [self rightBarButtonWithImageName:@"分享" selector:@selector(popShareSheet)];
}

- (void)popShareSheet{
    [self popSheet];
}


- (WPYNavBar *)sectionView {
    
    if (!_sectionView) {
        
        _sectionView = [[WPYNavBar alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 44) titleColor:kContentColor andSelectTitleColor:kThemeColor];
        _sectionView.delegate = self;
        _sectionView.titleFont = Font(14);
        [_sectionView AddNavBarArray:@[MYLocalizedString(@"TICKET_DESC", nil),MYLocalizedString(@"TICKET_PHURCHASE_TIP", nil)] isBtnLine:YES btnLineColor:kThemeColor];
        
        UIView * lineView = [[UIView alloc] init];
        lineView.backgroundColor = kBGColor;
        [_sectionView addSubview:lineView];
        
        [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.leading.equalTo(_sectionView.mas_leading).offset(16);
            make.trailing.equalTo(_sectionView.mas_trailing).offset(-16);
            make.bottom.equalTo(_sectionView.mas_bottom);
            make.height.mas_equalTo(1);
        }];
    }
    
    return _sectionView;
}

- (void)loadData {
    [ActivityIndicatorView showHUDAddedTo:self.view];
    
    [NetAPIManager getTicketDetailWithTicketID:self.ticketID block:^(TicketDetailModel *ticketDetailModel, NSError *error) {
        [ActivityIndicatorView hideHUDAddedTo:self.view];
        
        
        self.ticketDetailModel = ticketDetailModel;
        [self.TicketImageView setImageURL:[NSURL URLWithString:ticketDetailModel.pictureArray.firstObject] placeholderImage:kPlaceholderSqu];
        [self.tableView reloadData];
    }];
    
}
-(void)setup{
    
    UIView * headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenWidth * 9/16)];
    
    _TicketImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenWidth * 9/16)];
    _TicketImageView.image = [UIImage imageNamed:@"placeholder_squ"];
    _TicketImageView.contentMode =  UIViewContentModeScaleAspectFill;
    _TicketImageView.clipsToBounds = YES;
    [headerView addSubview:_TicketImageView];
    
    //    _tipBtn = [[UIButton alloc] initWithFrame:CGRectMake(kScreenWidth - 78, kScreenWidth * 3/4 - 26, 78, 26)];
    //    [_tipBtn setTitle:@"购票送讲解" forState:UIControlStateNormal];
    //
    //    [_tipBtn setBackgroundImage:[UIImage imageNamed:@"leftTopBg"] forState:UIControlStateNormal];
    //    [_tipBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    //    _tipBtn.titleLabel.font = Font(10);
    //    _tipBtn.userInteractionEnabled = NO;
    //    [headerView addSubview:_tipBtn];
    
    [self.reservationBtn setTitle:MYLocalizedString(@"TICKET_BOOK_BTN", nil) forState:UIControlStateNormal];
    self.tableView.backgroundColor = kBGColor;
    self.tableView.tableHeaderView = headerView;
    
    self.barBGAlpha = 0;
    
    [self setAutoRowHeight:self.tableView];
    
    [self closeAutomaticallyAdjustsScrollViewInsets:self.tableView];
    [self.tableView registerNib:[UINib nibWithNibName:@"TicketIntroduceCell" bundle:nil] forCellReuseIdentifier:@"TicketIntroduceCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"TicketInforTipCell" bundle:nil] forCellReuseIdentifier:@"TicketInforTipCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"TicketBookingCell" bundle:nil] forCellReuseIdentifier:@"TicketBookingCell"];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"TicketScenicCell" bundle:nil] forCellReuseIdentifier:@"TicketScenicCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"TicketPurchaseTipCell" bundle:nil] forCellReuseIdentifier:@"TicketPurchaseTipCell"];
    
    [self.tableView registerClass:[SectionTitleHeaderView class] forHeaderFooterViewReuseIdentifier:@"SectionTitleHeaderView"];
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.customBarStyle = UIStatusBarStyleLightContent;
}

- (IBAction)goReserveBtnClicked:(UIButton *)sender {
    
    if (![IGUtil hasLoginOrPresentLogin]) {
        
        return;
    }
    
    TicketOrderVC * vc = [[TicketOrderVC alloc] init];
    vc.ticketDetailModel = self.ticketDetailModel;
    
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark   -- WPYNavBarDelegate

- (void)selectChangetoViewNum:(NSInteger)num {
    NSIndexPath * indexPath;
    
    self.isDrag = NO;
    [self.tableView setContentInset:UIEdgeInsetsMake(kNavigationBarHeight, 0, 0, 0)];
    
    if (num == 0) {
        indexPath = [NSIndexPath indexPathForRow:0 inSection:2];
    }else{
        indexPath = [NSIndexPath indexPathForRow:0 inSection:3];
    }
    [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
}


- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat yOffset = self.tableView.contentOffset.y;
    CGFloat H = kScreenWidth/16 * 9;
    if (yOffset <= 0) {
        
        CGFloat factor = -yOffset + H ;
        CGRect f = CGRectMake(- (kScreenWidth * factor/H - kScreenWidth)/2, yOffset, kScreenWidth *factor/H, factor);
        self.TicketImageView.frame = f;
    }
    
    if (yOffset < H - kNavigationBarHeight  ) {
        
        CGFloat aplha = yOffset /(H -kNavigationBarHeight);
        
        self.barBGAlpha = aplha;
        self.customBarStyle = UIStatusBarStyleLightContent;
        scrollView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
        self.title = @"";
    }else {
        self.barBGAlpha = 1;
        self.customBarStyle = UIStatusBarStyleDefault;
        scrollView.contentInset = UIEdgeInsetsMake(kNavigationBarHeight, 0, 0, 0);
        self.title = self.ticketDetailModel.title;
    }
    
    
    if (!self.isDrag) {
        return;
    }
    
    CGRect rect = [self.tableView rectForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:2]];
    
    if (yOffset < (CGRectGetMaxY(rect) - kNavigationBarHeight - 44) - 10) {
        
        self.sectionView.selectIndex = 0;
    } else {
        
        rect = [self.tableView rectForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:3]];
        
        if (yOffset < (CGRectGetMaxY(rect) - kNavigationBarHeight - 44) - 10) {
            
            self.sectionView.selectIndex = 0;
        } else {
            
            self.sectionView.selectIndex = 1;
        }
    }
    
}


- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    
    self.isDrag = YES;
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    self.isDrag = NO;
}

- (BOOL)scrollViewShouldScrollToTop:(UIScrollView *)scrollView {
    self.isDrag = YES;
    
    [scrollView setContentOffset:CGPointZero animated:YES];
    return NO;
}
#pragma mark  --UITableViewDataSource,UITableViewDelegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    switch (section) {
        case 0:
            return 2;
            break;
        case 1:
            return self.ticketDetailModel.ticketTypes.count;
            break;
        case 2:
        {
            NSInteger num = 0;
            if (self.ticketDetailModel.detail.ticketIntroduction.content.length > 0) {
                
                num += 1;
            }
            
            return self.ticketDetailModel.detail.ticketIntroduction.pictures.count + num;
        }
            break;
        case 3:
        {
            if (self.ticketDetailModel.detail.ticketingNotes.length > 0) {
                return 1;
            }
        }
            break;
        default:
            break;
    }
    
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    switch (indexPath.section) {
        case 0:
        {
            if (indexPath.row == 0) {
                TicketIntroduceCell * cell = [tableView dequeueReusableCellWithIdentifier:@"TicketIntroduceCell"];
                [cell configDataWith:self.ticketDetailModel];
                
                return cell;
            }else{
                TicketInforTipCell * cell = [tableView dequeueReusableCellWithIdentifier:@"TicketInforTipCell"];
                if (self.ticketDetailModel) {
                    cell.TDmodel = self.ticketDetailModel;
                }
                return cell;
            }
            
        }
            break;
        case 1:
        {
            TicketBookingCell * cell = [tableView dequeueReusableCellWithIdentifier:@"TicketBookingCell"];
            cell.delegate = self;
            
            TicketTypeModel * model = self.ticketDetailModel.ticketTypes[indexPath.row];
            [cell configDataWith:model];
            
            return cell;
        }
            break;
        case 2:
        {
            if (indexPath.row == 0 && self.ticketDetailModel.detail.ticketingNotes.length > 0) {
                
                TicketPurchaseTipCell * cell = [tableView dequeueReusableCellWithIdentifier:@"TicketPurchaseTipCell"];
                [cell configDataWithTitle:[NSString stringWithFormat:@"%@：",MYLocalizedString(@"TICKET_DESC", nil)] Content:self.ticketDetailModel.detail.ticketIntroduction.content];
                return cell;
            }else{
                
                NSInteger num = 1;
                
                if (self.ticketDetailModel.detail.ticketingNotes.length == 0) {
                    num = 0;
                }
                TicketScenicCell * cell = [tableView dequeueReusableCellWithIdentifier:@"TicketScenicCell"];
                
                TicketDescModel * model = self.ticketDetailModel.detail.ticketIntroduction.pictures[indexPath.row - 1];
                
                [cell configDataWith:model];
                return cell;
            }
        }
            break;
        case 3:
        {
            TicketPurchaseTipCell * cell = [tableView dequeueReusableCellWithIdentifier:@"TicketPurchaseTipCell"];
            
            [cell configDataWithTitle:[NSString stringWithFormat:@"%@：",MYLocalizedString(@"TICKET_PHURCHASE_TIP", nil)] Content:self.ticketDetailModel.detail.ticketingNotes];
            return cell;
        }
            break;
        default:
            break;
    }
    
    return nil;
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    if (section == 2 && self.ticketDetailModel.detail.ticketingNotes.length > 0 && self.ticketDetailModel.detail.ticketIntroduction.content.length > 0) {
        
        return self.sectionView;
    }
    
    return nil;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    
    UITableViewHeaderFooterView * view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"footerView"];
    if (!view) {
        
        view = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:@"footerView"];
        view.contentView.backgroundColor = kBGColor;
    }
    return view;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    if (section == 2 && self.ticketDetailModel.detail.ticketingNotes.length > 0 && self.ticketDetailModel.detail.ticketIntroduction.content.length > 0) {
        
        return 44.f;
    }
    
    return 0.00001f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    if (section == 0) {
        
        return 0.0001;
    }
    
    return 10;
}


#pragma mark - SnailSheetViewDelegate

- (void)sheetView:(SnailSheetView *)sheetView didSelectItemAtSection:(NSInteger)section index:(NSInteger)index {
    
    //SnailSheetItemModel *model = [self sheetModels][section][index];
    
    //    NSString * descrbe = self.lineModel.type.integerValue == 1 ?MYLocalizedString(@"SHARE_LINE_MESSAGE", nil): MYLocalizedString(@"SHARE_SCENIC_MESSAGE", nil);
    
    // @weakify(self)
    self.sl_popupController.didDismiss = ^(SnailPopupController * _Nonnull popupController) {
        //  @strongify(self)
        
        //        [IGShare shareWebPageToPlatformType:model.platformType withURL:[NSString stringWithFormat:@"fxh5customline/%@",self.lineModel.lineid] title:self.lineModel.linename descr:descrbe thumImage:self.lineModel.pictures object:self.lineModel.playpath type:2 completion:^(id result, NSError *error) {
        //
        //        }];
    };
    [self.sl_popupController dismiss];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end

